//
//  XFAddCaseViewController.m
//  名医通
//
//  Created by mr.zhou on 16/7/11.
//  Copyright © 2016年 mr.zhou. All rights reserved.
//

#import "XFAddCaseViewController.h"
#import "XFChoseDiseaseViewController.h"
#import "XFNetWorkManager.h"
#import "XFModelTaibleViewController.h"
#import "XFSymptomViewController.h"
// 有关collectionView
#import "ZYTagLayout.h"
#import "NSString+ZYStringSize.h"

#import "XFSymptomPicCell.h"

#import "XFCaseFileModel.h"


@interface XFAddCaseViewController () <UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,ZYTagLayoutDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/**
 *  添加的病例模型
 */
@property (nonatomic,strong) XFCaseFileModel *caseModel;
/**
 *  病例列表
 */
@property (nonatomic,strong) NSMutableArray *caseList;
/**
 *  症状图片的数组
 */
@property (nonatomic,strong) NSMutableArray *symptomImages;
/**
 *  collectionView的高度是0de约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionZeroConstraint;
/**
 *  collectionView的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionHeightConstrant;
/**
 *  显示症状的collectionView
 */
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
/**
 *  选中的症状列表
 */
@property (nonatomic,strong) NSArray *symptomArray;
/**
 *  选择的疾病
 */
@property (nonatomic,assign) NSInteger selectedDisaeseId;

/**
 *  输入的疾病详情textView
 */
@property (weak, nonatomic) IBOutlet UITextView *textView;
/**
 *  占位符
 */
@property (nonatomic, strong)UILabel *lb;
/**
 *  疾病类型
 */
@property (weak, nonatomic) IBOutlet UILabel *diseaseType;
/**
 *  疾病细分类型
 */
@property (weak, nonatomic) IBOutlet UILabel *subDiseaseType;
/**
 *  点击选择疾病
 *
 *  @param sender
 */
- (IBAction)choseDisease:(id)sender;
/**
 *  点击疾病细分
 *
 *  @param sender
 */
- (IBAction)diseaseSubdivision:(id)sender;
/**
 *  添加疾病描述
 *
 *  @param sender
 */
- (IBAction)addDiseaseDescription:(id)sender;
/**
 *  点击照片选择
 */
- (IBAction)clickImagePicker:(id)sender;


@property (weak, nonatomic) IBOutlet UICollectionView *imageCollectionView;

@end

static NSString * XHLCellId = @"cellId";

@implementation XFAddCaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];

    [self setupCollectionView];

}

-(void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    [self.view setNeedsUpdateConstraints];



}

-(void)updateViewConstraints {

    if (self.symptomArray.count == 0 || self.symptomArray == nil) {
        
        _collectionZeroConstraint.constant = 0;
        
        
    } else {
        
        _collectionZeroConstraint.constant = 40;
    }
    
    [super updateViewConstraints];

}

- (void)setupCollectionView {
// 症状collectionView
    // 创建布局
    ZYTagLayout *layout = [[ZYTagLayout alloc] init];
    layout.delegate = self;
    // 创建CollectionView
    self.collectionView.collectionViewLayout = layout;
    _collectionView.dataSource = self;
    _collectionView.delegate   = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
    // 注册
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:XHLCellId];
//图片collectionView
    
    UICollectionViewFlowLayout *imageLayout = [[UICollectionViewFlowLayout alloc] init];
    
    imageLayout.itemSize = CGSizeMake(100, 100);
    
    imageLayout.minimumInteritemSpacing = 10;
    
    imageLayout.minimumLineSpacing = 10;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:(CGRectZero) collectionViewLayout:imageLayout];
    
    self.imageCollectionView = collectionView;
    
    self.imageCollectionView.backgroundColor = [UIColor whiteColor];
    
    
    self.imageCollectionView.delegate = self;
    
    self.imageCollectionView.dataSource = self;
    
    
    
}

-(void)setupUI {

    self.title = @"添加病例";

    self.textView.delegate = self;
    
    self.lb = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 21)];
    self.lb.text = @"我是占位符";
    self.lb.enabled = NO;
    [self.textView addSubview:self.lb];
    

}
#pragma mark - textView代理方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];//按回车取消第一相应者
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.lb.alpha = 0;//开始编辑时
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    //将要停止编辑(不是第一响应者时)
    if (textView.text.length == 0) {
        self.lb.alpha = 1;
    }
    return YES;
}

///  疾病类型选择
///
///  @param sender
- (IBAction)choseDisease:(id)sender {
    /**
     创建疾病选择列表控制器
     */
    XFChoseDiseaseViewController *choseVC = [[XFChoseDiseaseViewController alloc] init];
    
    __weak typeof(self) weakSelf = self;
    choseVC.didSelecetdRow = ^(NSString *name, NSInteger num) {
    
        weakSelf.diseaseType.text = name;
        
        weakSelf.selectedDisaeseId = num;
        
        [weakSelf.collectionView reloadData];
        
        //将名字存进病例model中
        weakSelf.caseModel = [[XFCaseFileModel alloc] init];
        
        weakSelf.caseModel.caseName = name;
        
        weakSelf.didAddedCaseBlock(weakSelf.caseModel);
        
    };
    [self.navigationController pushViewController:choseVC animated:YES];
    
}
///  疾病细分
///
///  @param sender
- (IBAction)diseaseSubdivision:(id)sender {
    
    if (self.selectedDisaeseId == 0) {
        
        // TODO: 用提示器
        NSLog(@"疾病不能为空");
    
        
        return;
    }else {
        __weak typeof(self) weakSelf = self;
        
        [[XFNetWorkManager shareManager] requestDiseaseSubdivisionWithDiseaseID:[NSString stringWithFormat:@"%zd",self.selectedDisaeseId] Complete:^(id responseData) {
            
            XFModelTaibleViewController *modelVC = [[XFModelTaibleViewController alloc] init];
            
            modelVC.didSelectedSubDisease = ^(NSString *name) {
            
                self.subDiseaseType.text = name;
            
            };
            
            modelVC.diseaseArray = (NSArray *)responseData;
            
            [weakSelf.navigationController pushViewController:modelVC animated:YES];
            
        }];
    
    }

}

///  添加疾病描述
///
///  @param sender
- (IBAction)addDiseaseDescription:(id)sender {
    
    XFSymptomViewController *symptomVC = [[XFSymptomViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    symptomVC.didSelectedSymptoms = ^(NSMutableArray *symptoms) {
        
        weakSelf.symptomArray = symptoms.copy;
        
        [self.collectionView reloadData];
        
    };
    
    [self.navigationController pushViewController:symptomVC animated:YES];
    
}
/**
 *  照片选则
 *
 *  @param sender
 */
- (IBAction)clickImagePicker:(id)sender {
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:YES completion:nil];
}


#pragma mark - collectionViewDatasource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.collectionView) {

        return self.symptomArray.count;
        
    }
    
    if (collectionView == self.imageCollectionView){
    
        //返回图片数组
        return self.symptomImages.count + 1;
        
    }
    return 0;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (collectionView == self.collectionView) {
        UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:XHLCellId forIndexPath:indexPath];
        NSInteger tag = 10;
        UILabel *label = (UILabel *)[cell.contentView viewWithTag:tag];
        if (label == nil) {
            label = [[UILabel alloc] init];
            label.tag = tag;
            label.font = [UIFont systemFontOfSize:18];
            label.textAlignment = NSTextAlignmentLeft;
            
        }
        label.text = self.symptomArray[indexPath.row];
        label.textColor = [UIColor blackColor];
        [label sizeToFit];
        [cell.contentView addSubview:label];
        
        cell.backgroundColor = [UIColor colorWithRed:82/255.0 green:175/255.0 blue:180/255.f alpha:1];
        return cell;

    }
    
    
    if (collectionView == self.imageCollectionView){
        
        //添加图片cell
        if (indexPath.item < self.symptomImages.count) {
        
            XFSymptomPicCell *cell = (XFSymptomPicCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"image" forIndexPath:indexPath];
            
            cell.imageVIew.image = self.symptomImages[indexPath.item];
            
            cell.clickDeleteButton = ^() {
            
                
            
            };
            
            return cell;
        } else {
        
            XFSymptomPicCell *cell = (XFSymptomPicCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"addImage" forIndexPath:indexPath];
            __weak typeof(self) weakSelf = self;
            
            cell.clickAddButtonBlock = ^() {
            
                UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                
                imagePicker.delegate = self;
                
                imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                
                
            };
            
            return cell;
        }
    
    }
    return nil;
}

#pragma mark -- ZYTagLayoutDelegate
- (CGSize)tagLabel:(UICollectionViewLayout *)tagLabel indexPath:(NSIndexPath *)indexPath {
    NSString *content = self.symptomArray[indexPath.row];

    return [content xhl_stringSizeWithFont:[UIFont systemFontOfSize:19]];
}
- (UIEdgeInsets)edgeInsetsInWaterFlowLayout:(UICollectionViewLayout *)layout {
    return UIEdgeInsetsMake(10, 10, 10, 15);
}
#pragma mark - imageViewDelegate
/**
 *  结束选择图片
 *
 *  @param picker
 *  @param image
 *  @param editingInfo
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {

    [self.symptomImages addObject:image];
    
}

#pragma mark - 病例列表懒加载
-(NSMutableArray *)caseList {

    if (_caseList == nil) {
    
        _caseList = [NSMutableArray array];
    
    }
    return _caseList;
}

#pragma mark - symptomsImages懒加载

-(NSArray *)symptomImages {

    if (_symptomImages == nil) {
    
        _symptomImages = [NSMutableArray array];
    
    }
    return _symptomImages;
}

@end
